// const utf8 = require('utf8');
// const axios = require('axios');

module.exports = function (options) {
    // koahub.logger.debug(options);
    /**
     * [getUrl description]
     * @param  {[type]} param [替换模板变量内容]
     * @param  {[type]} to    [短信接收手机号]
     * @return {[type]}       [promise]
     */

    let config = options;

    const getResult = function (param, mobile) {

        const url = 'https://open.ucpaas.com/ol/sms/sendsms';

        return koahub.curl({
            method: 'post',
            url: url,
            data: {
                sid: config.sid,
                token: config.token,
                appid: config.appid,
                templateid: config.templateid,
                param: param,
                mobile: mobile,
                uid: config.uid
            },
            headers: {
                "Content-Type": "application/json;charset=utf-8",
                "Accept": "application/json"
            }
        })

        // return axios({
        //     method: 'post',
        //     url: url,
        //     data: {
        //         sid: config.sid,
        //         token: config.token,
        //         appid: config.appid,
        //         templateid: config.templateid,
        //         param: param,
        //         mobile: mobile,
        //         uid: config.uid
        //     },
        //     headers: {
        //         "Content-Type": "application/json;charset=utf-8",
        //         "Accept": "application/json"
        //     }
        // })
    };

    return async function (ctx, next) {


        //调用实例：koahub.sendsms('87828,1','18928779564');
        koahub.sendsms = async function(param, mobile) {

            let data={};

            const response = await getResult(param, mobile);
            // console.log(response.data);
            // console.log(response.data.code);
            if (response.data.code == '000000') {
                data= {
                    message: '发送成功',
                    code: response.data
                };
            } else {
                data={
                    message: '请求失败',
                    code: response.data
                };
            }
            return  data;
        };

        await next();

    };
};